﻿/*
 * Copyright 2012 Rene Prost, Registrite ja Infosüsteemide Keskus 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

using System;
using System.Xml;
using System.Xml.Schema;
using Xtee.CodeDom.Wrapper;
using Xtee.Core;

namespace Xtee.CodeDom
{
    public static class XmlSchemaElementFactory
    {
        
        public static XmlSchemaElement Create(Xtee.Core.Services.Description.MessagePart part)
        {
            if (part.Type.IsEmpty)
            {
                throw new Exception("Cannot create element from empty type (MessagePart:" + part.Name + ")");
            }
            var elementType = part.Type.ToSchemaType(part.Message.Resolver);
            if (elementType == null)
            {
                throw new Exception(string.Format("Unable to locate ({0}) from schemas.",part.Type));
            }
            var el = new XmlSchemaElement();
            el.IsNillable = true;
            el.SchemaTypeName = part.Type;
            el.MinOccurs = 0;
            el.MaxOccurs = 1;
            el.Name = part.Name;
            el.SetElementType(elementType);
            el.SetQualifiedName(new XmlQualifiedName(part.Name, part.Message.Operation.Port.TargetNamespace.Namespace));
            return el;
        }

        public static XmlSchemaElement Create(XmlSchemaComplexContentRestriction fromRestriction,ISchemaObjectResolver resolver)
        {
            var arrayType = new ArrayType(fromRestriction);
            XmlSchemaType schemaType = arrayType.QualifiedName.ToSchemaType(resolver);

            if (schemaType == null)
            {
                throw new Exception("Could'nt find type [" + arrayType.QualifiedName + "] from schema!");
            }
            var el = new XmlSchemaElement();
            el.IsNillable = true;
            el.SchemaTypeName = arrayType.QualifiedName;
            el.MaxOccurs = decimal.MaxValue;
            el.Name = "item";
            el.SetElementType(schemaType);
            el.SetQualifiedName(new XmlQualifiedName("item", resolver.TargetNamespace.Namespace));
            return el;
        }
    }
}